<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category	CosmoCommerce
 * @package 	CosmoCommerce_99Bill
 * @copyright	Copyright (c) 2009 CosmoCommerce,LLC. (http://www.cosmocommerce.com)
 * @contact :
 * T: +86-021-66346672
 * L: Shanghai,China
 * M:sales@cosmocommerce.com
 */
class Globebill_Yandex_Model_Payment extends Mage_Payment_Model_Method_Abstract
{
    protected $_code  = 'yandex_payment';
    protected $_formBlockType = 'yandex/form';

    // yandex return codes of payment
    const RETURN_CODE_ACCEPTED      = 'Success';
    const RETURN_CODE_TEST_ACCEPTED = 'Success';
    const RETURN_CODE_ERROR         = 'Fail';

    // Payment configuration
    protected $_isGateway               = false;
    protected $_canAuthorize            = true;
    protected $_canCapture              = true;
    protected $_canCapturePartial       = false;
    protected $_canRefund               = false;
    protected $_canVoid                 = false;
    protected $_canUseInternal          = false;
    protected $_canUseCheckout          = true;
    protected $_canUseForMultishipping  = false;
    protected $_order                   = null;

    /**
     *  Returns Target URL
     *
     *  @return	  string Target URL
     */
    public function getYandexUrl()
    {
        $url = $this->getConfigData('transport_url');
        return $url;
    }

    /**
     *  Return back URL
     *
     *  @return	  string URL
     */
	protected function getReturnURL()
	{
		return Mage::getUrl('yandex/payment/return',  array('_secure' => true,'_nosid' => true));
	}

	/**
	 *  Return URL for yandex success response
	 *
	 *  @return	  string URL
	 */
	protected function getSuccessURL()
	{
		return Mage::getUrl('checkout/onepage/success', array('_secure' => true));
	}

    /**
     *  Return URL for yandex failure response
     *
     *  @return	  string URL
     */
    protected function getErrorURL()
    {
        return Mage::getUrl('yandex/payment/error', array('_secure' => true));
    }

	/**
	 *  Return URL for yandex notify response
	 *
	 *  @return	  string URL
	 */
	protected function getNotifyURL()
	{
		return Mage::getUrl('checkout/onepage/success', array('_secure' => true));
	}

    /**
     * Capture payment
     *
     * @param   Varien_Object $orderPayment
     * @return  Mage_Payment_Model_Abstract
     */
    public function capture(Varien_Object $payment, $amount)
    {
        $payment->setStatus(self::STATUS_APPROVED)
            ->setLastTransId($this->getTransactionId());

        return $this;
    }

    /**
     *  Form block description
     *
     *  @return	 object
     */
    public function createFormBlock($name)
    {
        $block = $this->getLayout()->createBlock('yandex/form_payment', $name);
        $block->setMethod($this->_code);
        $block->setPayment($this->getPayment());

        return $block;
    }

    /**
     *  Return Order Place Redirect URL
     *
     *  @return	  string Order Redirect URL
     */
    public function getOrderPlaceRedirectUrl()
    {
        return Mage::getUrl('yandex/payment/redirect');
    }

    /**
     *  Return Standard Checkout Form Fields for request to yandex
     *
     *  @return	  array Array of hidden form fields
     */
    public function getStandardCheckoutFormFields()
    {
        $session        = Mage::getSingleton('checkout/session');
        
        $order          = $this->getOrder();
        Mage::log(get_class($order));
        
        if (!($order instanceof Mage_Sales_Model_Order)) {
            Mage::throwException($this->_getHelper()->__('Cannot retrieve order object'));
        }
			
		//商户号
		$_merchant_no   = $this->getConfigData('merchant_no');
		
		//网关号
		$_gateway_no    = $this->getConfigData('gateway_no');
		
		//网关密匙
		$_signkey_code  = $this->getConfigData('signkey_code');
		
		//支付方式
		$_paymentMethod = 'Yandex';
		
		//订单号
		$_orderId       = $order->getRealOrderId();
		
		//支付币种(改为只用美元支付，烈)
		//$_ordercurrency = $order->getOrderCurrencyCode();
		$_ordercurrency = 'USD';
		
		//金额
		$_orderamount   = sprintf('%.2f', $order->getBaseGrandTotal());
		
		//返回地址
		$_returnUrl     = $this->getReturnURL();
		
		//备注
		$_remark        = $order->getRealOrderId();
		
		//校验源字符串
	 	$signsrc        = $_merchant_no.$_gateway_no.$_orderId.$_ordercurrency.$_orderamount.$_returnUrl.$_signkey_code;

		//生成加密签名串
		$_signinfo      = hash("sha256",$signsrc);
		
		//echo 'before:'.$signsrc.'<br>';
		//echo 'after:'.$_signinfo;

		//获取账单信息
		$billing        = $order->getBillingAddress();
		
		//账单人firstName
		$_firstName     = $billing->getFirstname();
		
		//账单人lastName
		$_lastName      = $billing->getLastname();
		
		//账单人email
		$_email         = $order->getCustomerEmail();
		
		//账单人电话
		$_phone         = $billing->getTelephone();
		
		//账单人国家
		$_country       = $billing->getCountry();
		
		//账单人州(可不提交)
		$_state         = $billing->getRegionCode();
		
		//账单人城市
		$_city          = $billing->getCity();
		
		//账单人地址
		$_address       = $billing->getStreet(1);
		
		//账单人邮编
		$_zip           = $billing->getPostcode();
		//邮编为空时，将随机成6位数字
		$temp = '';
		$rand='';
		for($i=0;$i<6;$i++)
		{
			$temp=rand(0,9);
			$rand.=$temp;
		}
		$_zip=empty($_zip)?$rand:$_zip;
		$interfaceInfo='magento';
		$interfaceVersion='V2.3';	
		$isMobile=$_SESSION['isMobile'];
		
	    $signMsgVal     = "";
	    $signMsgVal     = $this->appendParam( $signMsgVal , "merNo"         , $_merchant_no   );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "gatewayNo"     , $_gateway_no    );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "orderNo"       , $_orderId       );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "orderCurrency" , $_ordercurrency );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "orderAmount"   , $_orderamount   );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "returnUrl"     , $_returnUrl     );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "signInfo"      , $_signinfo      );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "firstName"     , $_firstName     );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "lastName"      , $_lastName      );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "email"         , $_email         );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "phone"         , $_phone         );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "remark"        , $_remark        );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "paymentMethod" , $_paymentMethod );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "country"       , $_country       );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "state"         , $_state         );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "city"          , $_city          );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "address"       , $_address       );
	    $signMsgVal     = $this->appendParam( $signMsgVal , "zip"           , $_zip           );
		
        //记录post log
	    $filedate = date('Y-m-d');
	    
	    $postdate = date('Y-m-d H:i:s');
	    
	    $newfile  = fopen( "globebill_log/" . $filedate . ".log", "a+" );
	    
	    $post_log = $postdate."[Merchant->GB(POST)]\r\n" . 
	 	            "merNo = "        .$_merchant_no . "\r\n".
	                "gatewayNo = "    .$_gateway_no . "\r\n".
         	        "orderNo = "      .$_orderId . "\r\n".
         	        "orderCurrency = ".$_ordercurrency . "\r\n".
         	        "orderAmount = "  .$_orderamount . "\r\n".
         	        "returnUrl = "    .$_returnUrl . "\r\n".
         	        "signInfo = "     .$_signinfo . "\r\n".
         	        "firstName = "    .$_firstName . "\r\n".
         	        "lastName = "     .$_lastName . "\r\n".
         	        "email = "        .$_email . "\r\n".
         	        "phone = "        .$_phone . "\r\n".
         	        "remark = "       .$_remark . "\r\n".
         	        "paymentMethod = ".$_paymentMethod . "\r\n".
         	        "country = "      .$_country . "\r\n".
         	        "state = "        .$_state . "\r\n".
         	        "city = "         .$_city . "\r\n".
         	        "address = "      .$_address . "\r\n".
         	        "zip = "          .$_zip . "\r\n".
					"interfaceInfo = ".$interfaceInfo . "\r\n".
					"interfaceVersion = ".$interfaceVersion . "\r\n".
					"isMobile = ".$isMobile . "\r\n";
	    
	    $post_log = $post_log . "*************************************\r\n";
	    
	    $post_log = $post_log.file_get_contents( "globebill_log/" . $filedate . ".log");
	    
	    $filename = fopen( "globebill_log/" . $filedate . ".log", "r+" );
	    
	    fwrite($filename,$post_log);
	    fclose($filename);
	    fclose($newfile);



		$parameter = array(
			               'merNo'          => $_merchant_no,
			               'gatewayNo'      => $_gateway_no,
			               'orderNo'        => $_orderId,
			               'orderCurrency'  => $_ordercurrency,
			               'orderAmount'    => $_orderamount,
			               'returnUrl'      => $_returnUrl,
			               'signInfo'       => $_signinfo,
			               'firstName'      => $_firstName,
			               'lastName'       => $_lastName,
			               'email'          => $_email,
			               'phone'          => $_phone,
			               'remark'         => $_remark,
			               'paymentMethod'  => $_paymentMethod,
			               'country'        => $_country,
			               'state'          => $_state,
			               'city'           => $_city,
			               'address'        => $_address,
			               'zip'            => $_zip,
						   'interfaceInfo'  => $interfaceInfo,
						   'interfaceVersion'=> $interfaceVersion,
						   'isMobile'       => $isMobile
		);
			
		//echo '<pre>';
		//print_r($parameter);
		//echo '</pre>';			
		
        return $parameter;
    }

	
	//功能函数。将变量值不为空的参数组成字符串
	public function appendParam($returnStr,$paramId,$paramValue){

		if($returnStr!=""){
			
				if($paramValue!=""){
					
					$returnStr.="&".$paramId."=".$paramValue;
				}
			
		}else{
		
			If($paramValue!=""){
				$returnStr=$paramId."=".$paramValue;
			}
		}
		
		return $returnStr;
	}
	//功能函数。将变量值不为空的参数组成字符串。结束	
	
	/**
	 * Return authorized languages by yandex
	 *
	 * @param	none
	 * @return	array
	 */
	protected function _getAuthorizedLanguages()
	{
		$languages = array();
		
        foreach (Mage::getConfig()->getNode('global/payment/creditcard_payment/languages')->asArray() as $data) 
		{
			$languages[$data['code']] = $data['name'];
		}
		
		return $languages;
	}
	
	/**
	 * Return language code to send to yandex
	 *
	 * @param	none
	 * @return	String
	 */
	protected function _getLanguageCode()
	{
		// Store language
		$language = strtoupper(substr(Mage::getStoreConfig('general/locale/code'), 0, 2));

		// Authorized Languages
		$authorized_languages = $this->_getAuthorizedLanguages();

		if (count($authorized_languages) === 1) 
		{
			$codes = array_keys($authorized_languages);
			return $codes[0];
		}
		
		if (array_key_exists($language, $authorized_languages)) 
		{
			return $language;
		}
		
		// By default we use language selected in store admin
		return $this->getConfigData('language');
	}



    /**
     *  Output failure response and stop the script
     *
     *  @param    none
     *  @return	  void
     */
    public function generateErrorResponse()
    {
        die($this->getErrorResponse());
    }

    /**
     *  Return response for yandex success payment
     *
     *  @param    none
     *  @return	  string Success response string
     */
    public function getSuccessResponse()
    {
        $response = array(
            'Pragma: no-cache',
            'Content-type : text/plain',
            'Version: 1',
            'OK'
        );
        return implode("\n", $response) . "\n";
    }

    /**
     *  Return response for yandex failure payment
     *
     *  @param    none
     *  @return	  string Failure response string
     */
    public function getErrorResponse()
    {
        $response = array(
            'Pragma: no-cache',
            'Content-type : text/plain',
            'Version: 1',
            'Document falsifie'
        );
        return implode("\n", $response) . "\n";
    }

}